import { searchItems } from '../../services/goods'
import { getMenuList } from '../../services/home'

Page({
  data: {
    categoryId: '',
    productName: '',
    productTag: '',

    sortWay: 0,
    sortType: 0,
    
    defaultTitle: "下拉刷新",
    pullRefresh: true,
    
    tabIndex: 0,
    isEnd: false,
    show: false, // 是否显示加载动画
    page: 1, // 当前页数

    list: [], // 页面List数据
    tablist: [],
    
    showRight: false,
    
    BrandList: [{ 'name': '华为' }, { 'name': '华为' }, { 'name': '华为' }, { 'name': '华为' }]
  },
  onLoad(event) {
    if (event.productName) {
      this.setData({ productName: event.productName })
    }
    if (event.categoryId) {
      this.setData({ categoryId: event.categoryId })
    }
    this.getMenuList()
    this.getProductList()
  },
  onShow() {
    my.setNavigationBar({
      title: '产品列表',
      backgroundColor: '#4BA3F9'
    })
  },
  searchgoods(e) {
    this.setData({ productName: e.detail.value, list: [], page: 1 })
    this.getProductList()
  },
  menuClick({ target: { dataset: { key } } }) {
    this.setData({ categoryId: key, page: 1, list: [] })
    this.getProductList()
  },
  tabClick(event) {
    this.setData({ tabIndex: event.target.dataset.num });
    this.setData({ sortType: event.target.dataset.num })
    my.startPullDownRefresh()
  },
  filtrate() {
    this.setData({ showRight: true });
  },
  onTopBtnTap() {
    this.setData({
      showRight: true,
    });
  },
  onPopupClose() {
    this.setData({
      showRight: false,
    });
  },
  onPullDownRefresh() {
    let that = this
    this.setData({
      list: [],
      page: 1,
      pages: 1
    });
    setTimeout(function () {
      that.getProductList()
    }, 1000)
  },
  stopPullDownRefresh() {
    my.stopPullDownRefresh()
  },
  async getMenuList() {
    const { code, data } = await getMenuList()

    if (code != 0) return false
    this.setData({ tablist: data.list.map(item => ({ tabName: item.name, tabIcon: item.icon })) })
  },
  async getProductList() {
    const { page, categoryId, productName, productTag, sortType, sortWay } = this.data

    const param = {
      sortType: sortType,
      sortWay: sortWay,
      page_num: page,
      type: categoryId,
      name: productName,
      tag: productTag,
    }

    this.setData({ show: true })

    const { code, data } = await searchItems(param)
    if (code != 0) return false
    
    this.setData({
      isEnd: data.list.length < 10,
      list: this.data.list.concat(data.list),
      page: page + 1,
      show: false
    })

    this.stopPullDownRefresh()
  },
  /**
  * scroll-view滑到底部触发事件
  * @method scrollMytrip
  */
  async scrollMytrip() {
    if (!this.data.isEnd) {
      this.getProductList()
    }
  }
});
